package com.sfx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sfx.domain.ResponseResult;
import com.sfx.domain.entity.Article;
import com.sfx.domain.vo.CategoryVo;
import com.sfx.service.ArticleService;
import com.sfx.utils.BeanCopyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sfx.mapper.CategoryMapper;
import com.sfx.domain.entity.Category;
import com.sfx.service.CategoryService;

import static com.sfx.constants.SystemConstants.ARTICLE_STATUS_NORMAL;
import static com.sfx.constants.SystemConstants.CATEGORY_STATUS_NORMAL;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private ArticleService articleService;
    /**
     * 查询文章分类列表
     * ①要求只展示有发布正式文章的分类 ②必须是正常状态的分类
     *
     * @return
     */
    @Override
    public ResponseResult getCategoryList() {
        //1.查询文章表的分类id有哪些进行去重
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Article::getStatus, ARTICLE_STATUS_NORMAL);
        List<Article> list = articleService.list(queryWrapper);
        //2.根据上面的文章查出分类id列表
        List<Long> ids = list.stream()
                .map(Article::getCategoryId).distinct().collect(Collectors.toList());
        //3.根据分类id查询分类列表
        List<Category> categories = listByIds(ids);
        categories = categories.stream().filter(category -> category.getStatus().equals(CATEGORY_STATUS_NORMAL)).collect(Collectors.toList());
        List<CategoryVo> categoryVos = BeanCopyUtils.copyBeanList(categories, CategoryVo.class);
        return ResponseResult.okResult(categoryVos);
    }
}